package com.example.myapplication.data.repository

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringSetPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "search_history")

@Singleton
class SearchHistoryRepository @Inject constructor(@ApplicationContext private val context: Context) {

    private object PreferencesKeys {
        val SEARCH_HISTORY_KEY = stringSetPreferencesKey("search_history")
    }

    val searchHistory: Flow<List<String>> = context.dataStore.data
        .map { preferences ->
            (preferences[PreferencesKeys.SEARCH_HISTORY_KEY] ?: emptySet()).toList().reversed() // Show most recent first
        }

    suspend fun addSearchTerm(term: String) {
        if (term.isBlank()) return
        context.dataStore.edit { settings ->
            val currentHistory = settings[PreferencesKeys.SEARCH_HISTORY_KEY] ?: emptySet()
            val newHistory = mutableSetOf<String>()
            newHistory.add(term.trim())
            newHistory.addAll(currentHistory)
            // Limit history size
            settings[PreferencesKeys.SEARCH_HISTORY_KEY] = newHistory.take(15).toSet()
        }
    }

    suspend fun clearHistory() {
        context.dataStore.edit { settings ->
            settings.remove(PreferencesKeys.SEARCH_HISTORY_KEY)
        }
    }
}
